package org.deltaset.faces.internal;

import org.deltaset.faces.OutcomeBuilder;

public class DefaultOutcomeBuilder implements OutcomeBuilder {

    private static final char QUESTION = '?';
    private static final char AMPERSAND = '&';
    private static final char EQUALS = '=';
    private static final String FACES_REDIRECT_KEY = "faces-redirect";
    private static final String FACES_REDIRECT_VALUE = "true";
    private final StringBuilder stringBuilder;
    private boolean facesRedirectAdded = false;
    private boolean parameterAdded = false;

    private char questionOrApmersand() {
        if (true == parameterAdded) {
            return AMPERSAND;
        } else {
            parameterAdded = true;
            return QUESTION;
        }
    }

    public DefaultOutcomeBuilder(String outcome) {
        this.stringBuilder = new StringBuilder(outcome);
    }

    @Override
    public OutcomeBuilder facesRedirect() {
        if (!facesRedirectAdded) {
            this.addParam(FACES_REDIRECT_KEY, FACES_REDIRECT_VALUE);
            facesRedirectAdded = true;
        }
        return this;
    }

    @Override
    public OutcomeBuilder addParam(String key, String value) {
        stringBuilder.append(questionOrApmersand()).append(key).append(EQUALS).append(value);
        return this;
    }

    @Override
    public String build() {
        return stringBuilder.toString();
    }
}
